package com.net.oil.http;

import com.net.oil.BuildConfig;
import com.net.oil.app.UserInfoManager;
import com.net.oil.http.custom.CustomGsonConverterFactory;
import com.net.oil.update.FileResponseBody;
import com.net.oil.util.AppInfo;
import com.net.oil.util.StringUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by lch on 2018/2/10 0010.
 *
 */

public class AppHttpClient {

    private static AppApi appApi, loginApi;

    private static Retrofit retrofit;

    private static Retrofit getRetrofit(String baseUrl){

        if (retrofit == null){

            final OkHttpClient.Builder builder = new OkHttpClient.Builder();

            Interceptor parameterInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    //公共参数
                    HttpUrl httpUrl = chain.request().url().newBuilder()
                            .addQueryParameter("platform", "android")
                            .addQueryParameter("version", AppInfo.getVersionName())
                            .build();
                    Request.Builder requestBuilder = chain.request().newBuilder()
                            .url(httpUrl);
                    return chain.proceed(requestBuilder.build());
                }
            };

            builder.addInterceptor(parameterInterceptor);

            if (UserInfoManager.getInstance().isLogin()){
                if (!StringUtil.isEmpty(UserInfoManager.getInstance().getToken())){
                    Interceptor headerInterceptor = new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request.Builder rBuilder = chain.request().newBuilder();
                            rBuilder.addHeader("token", UserInfoManager.getInstance().getToken());
                            return chain.proceed(rBuilder.build());
                        }
                    };
                    builder.addInterceptor(headerInterceptor);
                }
            }

            if (BuildConfig.DEBUG){
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(loggingInterceptor);
            }

            builder.connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .writeTimeout(20, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true);

            OkHttpClient client = builder.build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(CustomGsonConverterFactory.create())
                    .client(client)
                    .build();
        }

        return retrofit;
    }

    /**
     * 下载的api接口
     * @return  appApi
     */
    public static AppApi getDownLoadAppApi(){
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(12, TimeUnit.SECONDS)
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response response  = chain.proceed(chain.request());
                        return response
                                .newBuilder()
                                .body(new FileResponseBody(response))
                                .build();
                    }
                })
                .build();

        Retrofit retrofit =  new Retrofit.Builder()
                .client(client)
                .baseUrl(AppUrl.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(AppApi.class);
    }

    public static AppApi ApiService(){
        if (UserInfoManager.getInstance().isLogin()){
            if (loginApi == null){
                retrofit = null;
                loginApi = getRetrofit(AppUrl.BASE_URL).create(AppApi.class);
                appApi = null;
            }
            return loginApi;
        }else {
            if (appApi == null){
                retrofit = null;
                appApi = getRetrofit(AppUrl.BASE_URL).create(AppApi.class);
                loginApi = null;
            }

            return appApi;
        }

    }
}
